package com.information.manage.basic.common.utils.zip;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * zip压缩器
 */
public class ZipCompressor implements Closeable {

    private File tempFile;

    /**
     * key 压缩包中的路径
     * value 文件或folder
     */
    private Map<String, File> fileMap = new HashMap<>();


    public ZipCompressor() throws IOException {
        tempFile = File.createTempFile("cloud_", "zip");
    }

    public void putFile(String zipPath, File file){
        if(tempFile == null) return;
        fileMap.put(zipPath, file);
    }

    /**
     * 压缩
     */
    public void compress() throws IOException {
        if(tempFile == null) return;
        byte[] buffer = new byte[2048];
        int count = 0;
        try(ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(tempFile))){
            for (Map.Entry<String, File> entry : fileMap.entrySet()) {
                File file = entry.getValue();
                if(file.isDirectory()){
                    zipStream.putNextEntry(new ZipEntry(entry.getKey()));
                    zipStream.closeEntry();
                }else{
                    if (!file.exists()){
                        continue;
                    }
                    zipStream.putNextEntry(new ZipEntry(entry.getKey()));
                    // 文件压缩
                    try(FileInputStream inputStream = new FileInputStream(file)){
                        while((count = inputStream.read(buffer)) != -1){
                            zipStream.write(buffer, 0, count);
                        }
                        // 写完
                        zipStream.closeEntry();
                    }catch (IOException e){
                        throw e;
                    }
                }
            }
        }
    }

    /**
     * 获取文件流
     * @return
     * @throws FileNotFoundException
     */
    public InputStream getInputStream() throws FileNotFoundException {
        if(tempFile != null){
            return new FileInputStream(tempFile);
        }else {
            return null;
        }
    }

    @Override
    public void close() throws IOException {
        if(tempFile != null){
            tempFile.delete();
            tempFile = null;
        }
    }

}
